package com.pro_one.security;

import com.pro_one.pojo.Permission;
import com.pro_one.pojo.Role;
import com.pro_one.pojo.User;
import com.pro_one.service.PermissionService;
import com.pro_one.service.RoleService;
import com.pro_one.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;


    /**
     * 加载用户权限
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByUsername(username);
        if (user == null) {
            return null;
        }
        String password = user.getPassword();
        List list = new ArrayList();
        Set<Role> userRoles = user.getRoles();
        if (userRoles != null && userRoles.size() > 0) {
            for (Role userRole : userRoles) {
                list.add(new SimpleGrantedAuthority(userRole.getKeyword()));
                Set<Permission> permissions = userRole.getPermissions();
                if (permissions != null && permissions.size() > 0) {
                    for (Permission permission : permissions) {
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        return new org.springframework.security.core.userdetails.User(username, password, list);
    }
}
